package com.dycong.common.network;

import lombok.extern.log4j.Log4j;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;

import java.util.Optional;

/**
 * Created by dycong on 16-2-29.
 */
@Log4j
public class GlobalHttpClientProxy {

    static String proxyHost;

    public void setProxyHost(String proxyHost) {
        GlobalHttpClientProxy.proxyHost = proxyHost;
    }

    static int proxyPort;

    public void setProxyPort(int proxyPort) {
        GlobalHttpClientProxy.proxyPort = proxyPort;
    }

    static RequestConfig proxyRequestConfig;

    static boolean inited = false;

    public static void init() {
        try {
            if (!inited) {
                inited = true;
                if (proxyHost == null || proxyHost.equals("") || proxyPort == 0) {
                    //if not config, get from System.property
                    proxyHost = System.getProperty("http.proxyHost");
                    if (System.getProperty("http.proxyPort") != null) {
                        proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
                    }
                }
            }

            if (proxyHost == null || proxyHost.equals("") || proxyPort == 0) {
                //not set, ignore
                log.info("not set proxy, ignore");
            } else {
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                proxyRequestConfig = RequestConfig.custom().setProxy(proxy).build();
                log.info("set proxy from system config >> " + proxyHost + ":" + proxyPort);
            }
        } catch (RuntimeException e) {
            log.info("Init proxy from System config failed. " + e.toString());
            log.debug("", e);
        }

    }

    public static Optional<RequestConfig> getProxyRequestConfig() {
        if (!inited) {
            synchronized (GlobalHttpClientProxy.class) {
                init();
            }
        }
        return Optional.ofNullable(proxyRequestConfig);
    }


}
